#!/usr/bin/python

import argparse

from ros_introspection.util import get_packages

from roscompile import get_functions
from roscompile.diff import preview_changes
from roscompile.terminal import query_yes_no

all_functions = get_functions()
parser = argparse.ArgumentParser()
parser.add_argument('cmds', metavar='command', nargs='+')
parser.add_argument('-i', '--interactive', action='store_true')
args = parser.parse_args()

pkgs = get_packages()

print_options = False
for cmd in args.cmds:
    if cmd not in all_functions:
        print('Command {} not recognized'.format(cmd))
        print_options = True
if print_options:
    print()
    print('Available functions:')
    print('\n'.join(all_functions.keys()))
    exit(0)


for package in pkgs:
    for cmd in args.cmds:
        if args.interactive:
            if preview_changes(package, cmd, all_functions[cmd]):
                if query_yes_no('Would you like to make this change?'):
                    all_functions[cmd](package)
                    package.write()
                print()
        else:
            all_functions[cmd](package)
    package.write()
